package com.spring.demo5.eg1;

import org.junit.Test;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;

import java.lang.reflect.Method;

/**
 * @author vhans
 */
public class AopTest {
    /**
     * 模拟不同人员进行资金操作
     */
    @Test
    public void test() {
        // 代理工厂
        ProxyFactory proxyFactory = new ProxyFactory(new FundService());
        // 添加一个方法前置通知，判断用户名不为“Vhans”时，抛出非法访问异常
        proxyFactory.addAdvice(new MethodBeforeAdvice() {
            @Override
            public void before(Method method, Object[] args, Object target) throws Throwable {
                String name = (String) args[0];
                if (!"Vhans".equals(name)) {
                    throw new RuntimeException(String.format("「%s」非法访问!", name));
                }
            }
        });

        FundService proxy = (FundService) proxyFactory.getProxy();
        proxy.recharge("Vhans", 100);
        proxy.cashOut("盗贼", 10000);
    }


}
